var MongoClient = require('mongodb').MongoClient;
var async = require('async')
var ObjectId = require('mongodb').ObjectID;

var exports = module.exports

var getAggregations = function (connection, collection, key, callback) {
    MongoClient.connect(connection,
        function (err, db) {
            if (!err) {
                console.log("Connected to db!")
                var aggregator = [{$group: {_id: "$" + key, count: {$sum: 1}}}]
                db.collection(collection).aggregate(aggregator).toArray(function (err, docs) {
                    if(!err){
                        callback(docs)
                        db.close()
                    }else{
                        console.log("ERROR ->", err.errmsg)
                        db.close()
                    }
                })
            }
        });
}

//var coll = 'community'
//var connection = 'mongodb://120.55.126.201:27017/66xiaoqu';
//function printData(data) {
//    data.forEach(function (doc, i) {
//        console.log(doc)
//    })
//}
//getAggregations(connection, coll, 'city', printData)

exports.getAggregations = getAggregations
